package com.qf.smsplatform.strategy.impl;

import com.qf.smsplatform.client.CacheClient;
import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.Strategy;
import com.qf.smsplatform.util.PushMessage2Queue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service(value = "fee")
@Slf4j
public class FeeStrategy implements Strategy {

    @Autowired
    private CacheClient cacheClient;

    @Autowired
    private PushMessage2Queue pushMessage2Queue;

    @Override
    public boolean strategy(StandardSubmit submit) {
        log.info("【策略模块-扣费校验】 扣费校验策略开始执行！！");
        //1. 获取fee
        long fee = submit.getFee();
        //2. 通过hincr扣减当前客户信息中的fee
        Long balance = cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(),"fee",-fee);
        //3. 扣减的返回结果小于0,用户余额不足.
        if(balance < 0) {
            //4. 将扣减的费用添加回去,记录日志,发送两个消息,false
            cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(),"fee",fee);
            log.info("【策略模块-扣费校验】 扣费失败, 用户余额不足, fee = {}",balance + fee);
            pushMessage2Queue.sendLogMessage(submit, StrategyConstants.STRATEGY_ERROR_FEE);
            pushMessage2Queue.pushReportMessage(submit, StrategyConstants.STRATEGY_ERROR_FEE);
            return false;
        }
        log.info("【策略模块-扣费校验】 扣费校验策略执行结束！！");
        return true;
    }
}
